import router from '@/router'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { ref, reactive, watch } from 'vue'
import { useFullScreen } from '@/hooks/useFullScreen'

// 全局变量
const { toggleFull } = useFullScreen() // 全屏

export const useTabsStore = defineStore('tabs', () => {
  const tabs = reactive([
    JSON.parse(sessionStorage.getItem('qf-fengneng-pro-tab')) || {
      path: '/dashboard',
      label: '仪表盘'
    }
  ])

  const tabsName = ref(tabs[0].path)
  watch(tabsName, () => {
    router.push(tabsName.value)
  })

  const jump = (row) => {
    onTabsAdd(row)
  }

  const onTabsAdd = (row) => {
    const findIndex = tabs.findIndex((item) => {
      return item.path === row.path
    })
    if (findIndex === -1) tabs.push(row)

    sessionStorage.setItem('qf-fengneng-pro-tab', JSON.stringify(row)) // 刷新数据持久化

    tabsName.value = row.path
  }

  const onTabsDelete = (path) => {
    if (tabs.length <= 1) {
      ElMessage.info('至少保留一个选项卡')
      return
    }

    tabs.forEach((item, i) => {
      if (path === item.path) {
        tabs.splice(i, 1)
        // 删除后跳转前一个
        tabsName.value = tabs[tabs.length - 1].path
      }
    })
  }

  const onReload = () => {
    router.replace(tabsName.value)
  }

  const onFullScreen = () => {
    toggleFull(document.querySelector('.content'), '#f0f2f5')
  }

  const onCloseCurrent = () => {
    onTabsDelete(tabsName.value)
  }

  const onCloseOther = () => {
    const tab = tabs.find((item) => {
      return tabsName.value === item.path
    })

    if (tab) {
      tabs.splice(0, 9999999)
      tabs.push(tab)
    }
  }

  const onCloseAll = () => {
    tabs.splice(0, 9999999)
    // 保留跳转默认
    tabs.push({ path: '/dashboard', label: '仪表盘' })
    tabsName.value = '/dashboard'
  }

  return {
    jump,
    tabs,
    tabsName,
    onTabsAdd,
    onTabsDelete,
    onReload,
    onFullScreen,
    onCloseCurrent,
    onCloseOther,
    onCloseAll
  }
})
